//
//  PlayerViewController.m
//  GSG
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "PlayerViewController.h"
#import"AFSoundManager.h"

#import"MainPageViewController.h"
#import <ShareSDK/ShareSDK.h>
#import "PlayListViewController.h"

#import <ShareSDK/ShareSDK.h>

#import"SongModel.h"
#import "singleSong.h"
#import "Singleton.h"

@interface PlayerViewController ()

@property(nonatomic,retain)UISlider *soundSlider;//音量的slider
@property(nonatomic,retain)UISlider *slider1;//歌曲进度slider
@property (nonatomic, retain)UIButton *playRemoteButton;//总播放按钮
@property (nonatomic, retain)UIButton *playButton;//播放按钮
@property (nonatomic, retain)UILabel *elapsedTime;//已经播放的时间
@property (nonatomic, retain)UILabel *timeRemaining;//剩余的时间
@property(nonatomic,copy)NSString *str;
@property(nonatomic,assign)int  flag;//控制play按钮图片变化
@property(nonatomic,assign)int flag1;//控制播放类型按钮图片变化
@property(nonatomic,retain)UIButton*button;
@property(nonatomic,retain)NSURL *url;
@property(nonatomic,assign)NSInteger i;//歌曲数组里元素的下标;
@property(nonatomic,retain)NSMutableDictionary*dic;
@property(nonatomic,retain)UILabel *songLabel;//歌曲的名字
@property(nonatomic,retain)UILabel *singerLabel;//歌手的名字

@property (nonatomic, retain)UIButton *shareButton;//第三方分享
@property(nonatomic,retain)UIButton* collect;  // 收藏

@property(nonatomic,retain)UIButton *palyType;//播放类型
@property(nonatomic,retain)UIButton *bu;
@property(nonatomic,assign)NSInteger flag2;//实现单曲循环的值
@property(nonatomic,assign)NSInteger flag3;//实现随机播放的值
@property(nonatomic,retain)UIButton *bunext;
@property(nonatomic,retain)UIAlertView *alterRefuse;
@property(nonatomic,retain)UIAlertView *alterRandom;
@property(nonatomic,retain)UIAlertView *alterOrder;
@end

@implementation PlayerViewController

- (void)dealloc
{
    [_soundSlider release];
    [_slider1 release];
    [_elapsedTime release];
    [_timeRemaining release];
    [_dic release];
    [_songLabel release];
    [_singerLabel release];
    [_palyType release];
    [_bu release];
    [_bunext release];
    [_alterOrder release];
    [_alterRandom release];
    [_alterRefuse release];
    
    [super dealloc];
}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{

    self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
        self.flag=0;
        self.flag1=0;
    }
    return self;
}

-(void)create
{
    for (SongModel  *ssm in self.arr) {

//        NSLog(@"%@",ssm.url);
//        NSLog(@"%@",ssm.song_name);
//        NSLog(@"%@",ssm.singer_name);

        

        ssm=self.arr[_i];
        self.str=ssm.url;
        self.songLabel.text=ssm.singer_name;
        self.singerLabel.text=ssm.song_name;

   
    }
   
    self.song = self.arr[_i];
    [[AFSoundManager sharedManager]pause];//把当前的音乐暂停
    [self playRemoteFile];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    [singleSong shareSingleSong].arrSong=self.arr;
   

     
    self.view.backgroundColor=[UIColor whiteColor];
    
//    self.collect=[UIButton buttonWithType:UIButtonTypeSystem];
//    self.collect.frame=CGRectMake(self.view.frame.size.width * 100 / 375, self.view.frame.size.height * 130 / 667, self.view.frame.size.width * 40 / 375, self.view.frame.size.height * 40 / 667);
//    [self.collect setTitle:@"收藏" forState:UIControlStateNormal];
//    [self.collect addTarget:self action:@selector(touchcollect) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:self.collect];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"shoucang之前.png"] style:UIBarButtonItemStylePlain target:self action:@selector(touchcollect)];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"shoucang之前.png"] landscapeImagePhone:[UIImage imageNamed:@"shoucang.png"] style:UIBarButtonItemStylePlain target:self action:@selector(touchcollect)];


    self.shareButton=[UIButton buttonWithType:UIButtonTypeCustom];
    self.shareButton.frame=CGRectMake(self.view.frame.size.width * 20 / 375, self.view.frame.size.height * 15 / 667+64, self.view.frame.size.width * 40/ 375, self.view.frame.size.height *40 / 667);
    [self.shareButton setImage:[UIImage imageNamed:@"fenxiang"] forState:UIControlStateNormal];
//    [self.shareButton setTitle:@"分享" forState:UIControlStateNormal];
    [self.shareButton addTarget:self action:@selector(touch) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.shareButton];
    

    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bujing.png"]];
    self.songLabel=[[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 87.5 / 375, self.view.frame.size.height * 40 / 667+64, self.view.frame.size.width * 200 / 375, self.view.frame.size.height * 40 / 667)];
    self.songLabel.font=[UIFont systemFontOfSize:18];
    self.songLabel.textAlignment=1;
    [self.view addSubview:self.songLabel];
    [_songLabel release];
    self.singerLabel=[[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 107.5 / 375, self.view.frame.size.height * 10 / 667+64, self.view.frame.size.width * 160 / 375, self.view.frame.size.height * 30 / 667)];
    self.singerLabel.textAlignment=1;
    [self.view addSubview:self.singerLabel];
    [self.singerLabel release];
    
    
    UIView *viewRoll=[[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 87.5 / 375, self.view.frame.size.height * 190 / 667, self.view.frame.size.width * 200 / 375, self.view.frame.size.height * 200 / 667)];
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width * 200 / 375, self.view.frame.size.height * 200 / 667)];
    [image setImage:[UIImage imageNamed:@"tu.png"]];
    [viewRoll addSubview:image];
    viewRoll.layer.cornerRadius=100;
    [self.view addSubview:viewRoll];
    [viewRoll release];
    
    //放歌
    self.i = self.num;
    [self create];
    
    
    
    self.elapsedTime=[[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 107.5 / 375, self.view.frame.size.height * 80 / 667+64, self.view.frame.size.width * 160 / 375, self.view.frame.size.height * 30 / 667)];
    self.elapsedTime.textAlignment=1;
    [self.view addSubview:self.elapsedTime];

    [self setNeedsStatusBarAppearanceUpdate];
    [self.elapsedTime release];

    self.timeRemaining=[[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 200 / 375, self.view.frame.size.height * 600 / 667, self.view.frame.size.width * 160 / 375, self.view.frame.size.height * 30 / 667)];
    self.elapsedTime.textAlignment=1;
    [self.view addSubview:self.timeRemaining];
    self.timeRemaining.hidden=YES;
    [self.timeRemaining release];
    
    
    [self setNeedsStatusBarAppearanceUpdate];
    
    //进度条的背景
    self.slider1=[[UISlider alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 30 / 375, self.view.frame.size.height * 450 / 667, self.view.frame.size.width * 316 / 375, self.view.frame.size.height * 20 / 667)];
    [self.view addSubview:self.slider1];
    _slider1.value=0;
    
    [self.slider1 setMinimumTrackImage:[UIImage imageNamed:@"tiao.png"] forState:UIControlStateNormal];
    [self.slider1 setMaximumTrackImage:[UIImage imageNamed:@"tiao.png"] forState:UIControlStateNormal];
    [self.slider1 setThumbImage:[UIImage imageNamed:@"huakuai.png"] forState:UIControlStateHighlighted];
    [self.slider1 setThumbImage:[UIImage imageNamed:@"huakuai.png"]  forState:UIControlStateNormal];
    [self.slider1  addTarget:self action:@selector(songTime1:) forControlEvents:UIControlEventValueChanged];

    [self.slider1 release];

    
    //页面的按钮
    self.button=[UIButton buttonWithType:UIButtonTypeSystem];
    self.button.frame=CGRectMake(self.view.frame.size.width * 137 / 375, self.view.frame.size.height * 530 / 667, self.view.frame.size.width * 100 / 375, self.view.frame.size.height * 100 / 667);
    [self.button setBackgroundImage:[UIImage imageNamed:@"tingzhi.png"] forState:UIControlStateNormal];
    [self.view addSubview:self.button];
    
    
    UIButton *bulast=[UIButton buttonWithType:UIButtonTypeSystem];
    bulast.frame=CGRectMake(self.view.frame.size.width * 25 / 375, self.view.frame.size.height * 573 / 667, self.view.frame.size.width * 70 / 375, self.view.frame.size.height * 35 / 667);
    [bulast setBackgroundImage:[UIImage imageNamed:@"shangyiqu"] forState:UIControlStateNormal];
    [bulast addTarget:self action:@selector(lastSong) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bulast];
    
    
    self.bunext=[UIButton buttonWithType:UIButtonTypeSystem];
    _bunext.frame=CGRectMake(self.view.frame.size.width * 280 / 375, self.view.frame.size.height * 573 / 667, self.view.frame.size.width * 70 / 375, self.view.frame.size.height * 35 / 667);
    [_bunext setBackgroundImage:[UIImage imageNamed:@"xiayiqu"] forState:UIControlStateNormal];
    [_bunext addTarget:self action:@selector(nextSong) forControlEvents:UIControlEventTouchUpInside];
    if (self.arr.count==1) {
        self.bunext.enabled=NO;
    }
    [self.view addSubview:_bunext];
    
    
    self.playButton=[UIButton buttonWithType:UIButtonTypeSystem];
    self.playButton.frame=CGRectMake(self.view.frame.size.width * 137 / 375, self.view.frame.size.height * 535 / 667, self.view.frame.size.width * 100 / 375, self.view.frame.size.height * 100 / 667);
    self.playButton.layer.cornerRadius=50;
    [self.playButton addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.playButton];
   
    
    _bu=[UIButton buttonWithType:UIButtonTypeSystem];
    _bu.frame=CGRectMake(self.view.frame.size.width * 320 / 375, self.view.frame.size.height * 15 / 667+64, self.view.frame.size.width * 40 / 375, self.view.frame.size.height * 40 / 667);
    [ _bu setBackgroundImage:[UIImage imageNamed:@"shunxu.png"] forState:UIControlStateNormal];

    [self.view addSubview:self.bu];
    
    
    _palyType=[UIButton buttonWithType:UIButtonTypeSystem];
    _palyType.frame=CGRectMake(self.view.frame.size.width * 320 / 375, self.view.frame.size.height * 15 / 667+64, self.view.frame.size.width * 40/ 375, self.view.frame.size.height * 40/ 667);
    [_palyType addTarget:self action:@selector(playType) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_palyType];
 
    self.alterRefuse=[[UIAlertView alloc]initWithTitle:@"播放模式" message:@"单曲循环" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    
    self.alterRandom=[[UIAlertView alloc]initWithTitle:@"播放模式" message:@"随机播放" delegate:self cancelButtonTitle:@"确定"otherButtonTitles:nil, nil];
    
  self.alterOrder=[[UIAlertView alloc]initWithTitle:@"播放模式" message:@"顺序播放" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    [self.view addSubview:self.alterOrder];
    [self.view addSubview:self.alterRandom];
    [self.view addSubview:self.alterRefuse];


   }



-(void)playType{
    _bu.hidden=YES;
    switch (self.flag1) {
        case 0:
            [_palyType  setBackgroundImage:[UIImage imageNamed:@"xunhuan.png"] forState:UIControlStateNormal];
            //实现单曲循环
            [self.alterRefuse show];
            
            self.flag1=2;
            self.flag2=1;
            break;

        case 2:
              [_palyType  setBackgroundImage:[UIImage imageNamed:@"shunxu.png"] forState:UIControlStateNormal];
            [self.alterOrder show];
            self.flag1=0;
            self.flag2=2;
            self.flag3=2;
            break;
            
    }
    
    

    
}
-(void)nextSong
{
    
        if(_i <= self.arr.count-2){
        _i++;

    }
//    NSLog(@"%ld",_i);
    [self create];

    
//    NSLog(@"%ld",_i);
        [self create];
        if(_i==self.arr.count-1){
//        UIAlertView *show=[[UIAlertView alloc]initWithTitle:@"提示" message:@"已经是最后一首" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        
//        [show show];
     
    }
}


-(void)lastSong
{
    if(_i > 0){
        _i--;
    }
//    NSLog(@"%ld",_i);
    [self create];
}

-(void)playRemoteFile
{
    [[AFSoundManager sharedManager]startStreamingRemoteAudioFromURL:self.str andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
        if (!error) {
            //时间的格式
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"mm:ss"];
            NSDate *elapsedTimeDate = [NSDate dateWithTimeIntervalSince1970:elapsedTime];
            _elapsedTime.text = [formatter stringFromDate:elapsedTimeDate];
            NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSince1970:timeRemaining];
            _timeRemaining.text = [formatter stringFromDate:timeRemainingDate];

            
            if([_timeRemaining.text isEqualToString:@"00:01"]){
                if(self.flag2==1){
                    [[AFSoundManager sharedManager]restart];
                }
                if(self.flag3==1){
                    _i=arc4random() %10;
                
                }
              if(self.flag1==0){
                  if(_i<self.arr.count-1){
                    [self nextSong];
               
                }
                  if (_i==self.arr.count-1) {
                      [[AFSoundManager sharedManager]stop];
                      
                  }
                         }
          }
            if([_timeRemaining.text isEqualToString:@"00:00" ]&&![_elapsedTime.text  isEqual:@"00:00"]){
                [[AFSoundManager sharedManager]pause ];
            }
            _slider1.value = percentage * 0.01;
        }
        else {
            NSLog(@"There has been an error playing the remote file: %@", [error description]);
        }
        
    }];
    
}
-(void)action
{
    self.button.hidden=YES;
    if (self.flag==0) {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"bofang.png"] forState:UIControlStateNormal];
        [[AFSoundManager sharedManager]pause];
        self.flag=1;
    } else {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"tingzhi.png"] forState:UIControlStateNormal];
        [[AFSoundManager sharedManager]resume];
        self.flag=0;
    }
    
}

-(void)pauseAudio
{
    [[AFSoundManager sharedManager]pause];
}

-(void)resume
{
    [[AFSoundManager sharedManager]resume];
}

//重新开始
-(void)restart
{
    [[AFSoundManager sharedManager]restart];
}

//声音控制
-(void)sound
{
    [[AFSoundManager sharedManager] changeVolumeToValue:self.soundSlider.value];
}

//时间控制
-(void)songTime1:(UISlider *)sender
{
    [[AFSoundManager sharedManager]moveToSection:sender.value];
}

- (void)touch{
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
    
    NSString *str =self.song.song_name;
    NSString *str1 = self.song.singer_name;
    NSString *str3 = self.song.url;
    NSString *str2 = [NSString stringWithFormat:@"我在听《%@-%@》,你也来听吧! %@（分享自@1丶year 音乐客户端）",str,str1,str3];
//    NSLog(@"%@",str);
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:str2
                                       defaultContent:@"测试一下"
                                                image:[ShareSDK imageWithPath:imagePath]
                                                title:@"ShareSDK"
                                                  url:@"http://www.mob.com"
                                          description:@"这是一条测试信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    //    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
        UIAlertView *aler = [[UIAlertView alloc] initWithTitle:@"提示" message:@"分享成功" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil,nil];
                                    [aler show];
                                    [aler release];
                                    
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                }
                            }];

}

// 收藏
- (void)touchcollect{
    [[Singleton shareSingleton] openDB];
    [[Singleton shareSingleton] createTable];
    
    
    int flag = 0;
    NSMutableArray *arr = [[Singleton shareSingleton] selectLand];
    
    for (Code *code in arr) {
        if ([code.songName isEqualToString:self.song.song_name]) {
            // [self showMessage:@"已收藏"];
//            NSLog(@"已经收藏");
            UIAlertView *aler = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil,nil];
            [aler show];
            [aler release];

            flag = 1;
        }
    }
    if(flag == 0){
        //插入数据
        
        Code *code = [[Code alloc] init];
        code.songName = self.song.song_name;
        code.singerName = self.song.singer_name;
        code.url = self.song.url;
        [[Singleton shareSingleton] insertLand:code];
        
        UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-75, self.view.frame.size.height/2-32.5, 150, 65)];
        view2.backgroundColor = [UIColor whiteColor];
        view2.alpha = 0.8;
        UILabel *label = [[UILabel alloc] init];
        label.text = @"收藏成功";
        label.textAlignment = NSTextAlignmentCenter;
        label.frame = CGRectMake(view2.frame.size.width/2-50, view2.frame.size.height/2-20, 100, 40);
        [view2 addSubview:label];
        
        [self.view addSubview:view2];
        [UIView animateWithDuration:2 animations:^{
            view2.alpha = 0;
        } completion:^(BOOL finished) {
            [view2 removeFromSuperview];
        }];
        
        [label release];
        [view2 release];
        
        
    }
    
}

- (void)didReceiveMemoryWarning
{

    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
